
package ar.edu.caece.compiler.helpers;

import static java.lang.ClassLoader.getSystemResource;
import static java.lang.Thread.currentThread;
import static java.net.URLDecoder.decode;
import static org.apache.commons.logging.LogFactory.getLog;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;

import org.apache.commons.logging.Log;

/**
 * Load resources (or images) from various sources.
 * 
 */

public class FileLocator {

    private static Log logger = getLog(FileLocator.class);

    private static final String TSTR = "Caught Exception while in Loader.getResource. This may be innocuous.";

    public static String getPath(String resource, String enconding) throws UnsupportedEncodingException {
    	return decode(getResource(resource).getPath(), enconding);
    }
    
    /**
     * This method will search for <code>resource</code> in different places.
     * The search order is as follows:
     * 
     * <ol>
     * 
     * <p>
     * <li>Search for <code>resource</code> using the thread context class
     * loader under Java2. If that fails, search for <code>resource</code>
     * using the class loader that loaded this class (<code>Loader</code>).
     * Under JDK 1.1, only the the class loader that loaded this class (<code>Loader</code>)
     * is used.
     * 
     * <p>
     * <li>Try one last time with
     * <code>ClassLoader.getSystemResource(resource)</code>, that is is using
     * the system class loader in JDK 1.2 and virtual machine's built-in class
     * loader in JDK 1.1.
     * 
     * </ol>
     */
    static public URL getResource(String resource) {
        ClassLoader classLoader = null;
        URL url = null;

        try {

            classLoader = getTCL();
            if (classLoader != null) {
                logger.debug("Trying to find [" + resource + "] using context classloader");
                url = classLoader.getResource(resource);
                if (url != null)
                    return url;
            }

            // We could not find resource. Ler us now try with the classloader that loaded this class.
            classLoader = FileLocator.class.getClassLoader();
            if (classLoader != null) {
                logger.debug("Trying to find [" + resource + "] using " + classLoader + " class loader.");
                url = classLoader.getResource(resource);
                if (url != null)
                    return url;
            }
        } catch (Throwable t) {
            logger.warn(TSTR, t);
        }

        // Last ditch attempt: get the resource from the class path. It
        // may be the case that clazz was loaded by the Extentsion class
        // loader which the parent of the system class loader. Hence the
        // code below.
        logger.debug("Trying to find [" + resource + "] using ClassLoader.getSystemResource().");
        return getSystemResource(resource);
    }

    /**
     * Get the Thread Context Loader which is a JDK 1.2 feature. If we are
     * running under JDK 1.1 or anything else goes wrong the method returns
     * <code>null<code>.
     *
     */
    private static ClassLoader getTCL() throws IllegalAccessException, InvocationTargetException {

        // Are we running on a JDK 1.2 or later system?
        Method method = null;
        try {
            method = Thread.class.getMethod("getContextClassLoader");
        } catch (NoSuchMethodException e) {
            // We are running on JDK 1.1
            return null;
        }

        return (ClassLoader) method.invoke(currentThread());
    }    
}
